using System;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Description;
using System.Collections.ObjectModel;

namespace Caramel.ServiceModel
{
	public class PerCallLocalStorageServiceBehavior : IServiceBehavior
	{
		#region IServiceBehavior Members

		public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
		{
		}

		public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
		{
			var operations =
				serviceHostBase.
					ChannelDispatchers.
					OfType<ChannelDispatcher>().
					Cast<ChannelDispatcher>().
					SelectMany(d => d.Endpoints).
					SelectMany(e => e.DispatchRuntime.Operations);

			foreach (var operation in operations)
			{
				operation.CallContextInitializers.Add(new PerCallLocalStorageCallContextInitializer());
			}
		}

		public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
		{
		}

		#endregion
	}
}
